#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""唯一进程锁"""

import os
import sys
import traceback

from common.pathmgr import PathConfig
from common.filelocker import FileLocker, HasBeenLockedError


class UniqueProcess(object):
    def __init__(self, uniqueProcessName=None, pn=0):
        self.uniqueProcessName = uniqueProcessName
        if not self.uniqueProcessName:
            code_path = traceback.extract_stack()[0][0]
            if code_path and code_path.lower().startswith(PathConfig.PROJECT_FOLDER.lower()):
                code_path = code_path[len(PathConfig.PROJECT_FOLDER):]
                if code_path[0] in ("\\", "/"):
                    code_path = code_path[1:]
                filename = code_path.replace("\\", ".").replace("/", ".")
            else:
                filename = os.path.basename(code_path)
            self.uniqueProcessName = os.path.splitext(filename)[0]

        self.locker = FileLocker("Ga9!rVeqexgdang$%s%d" % (self.uniqueProcessName, pn))

    def check(self):
        try:
            self.locker.lock(True)
        except HasBeenLockedError:
            print('%s is running, can`t run another!' % self.uniqueProcessName)
            sys.exit()

    def check2(self):
        try:
            self.locker.lock(True)
            return True
        except HasBeenLockedError:
            print('%s is running, can`t run another!' % self.uniqueProcessName)
            return False

    def __del__(self):
        self.locker.unlock()


if __name__ == "__main__":
    u = UniqueProcess("test")
    u.check()
